package cn.tedu.simulateioc2;/**
 * @Author 金帮嘉诚 @Date 2021-07-16 星期五 19:45
 */
/*本类用于测试*/

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 知识点
 */
public class MyIoC2 {
    private List<Bean2> bean2Factory = new ArrayList<>();
    private final Map<String, Object> factoryBean2Object = new ConcurrentHashMap<>();

    {
        Bean2 bean21 = new Bean2("hello2", "cn.tedu.simulateioc2.Hello2");
        Bean2 bean22 = new Bean2("sun2", "cn.tedu.simulateioc2.Sun2");
        Bean2 bean23 = new Bean2("user2", "cn.tedu.simulateioc2.User2");

//        System.out.println(bean2Factory);//[]
        bean2Factory.add(bean21);
        bean2Factory.add(bean22);
        bean2Factory.add(bean23);
        try {
//            System.out.println("CB111~~~~");
            init();
//            System.out.println("CB222~~~~");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

//    public MyIoC2() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
//        Bean2 bean21 = new Bean2("hello2", "cn.tedu.simulateioc2.Hello2");
//        Bean2 bean22 = new Bean2("sun2", "cn.tedu.simulateioc2.Sun2");
//        Bean2 bean23 = new Bean2("user2", "cn.tedu.simulateioc2.User2");
//
//        bean2Factory.add(bean21);
//        bean2Factory.add(bean22);
//        bean2Factory.add(bean23);
//        init();
//    }


    private void init() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//        System.out.println("init111");
        for (Bean2 b : bean2Factory
        ) {
//            System.out.println(b);
            String key = b.getBeanName();
            String path = b.getBeanPath();
            Object value = Class.forName(path).newInstance();

//            System.out.println(factoryBean2Object);//null
            //构造代码块中这句出错
            factoryBean2Object.put(key, value);
//            System.out.println(b);
        }
    }

    public Object getBean2(String bean2Name) {
        return factoryBean2Object.get(bean2Name);
    }

}
